package study;

import java.util.Arrays;

public class MaxSubArray {

    // 学习官方分治解法
    public int maxSubArray(int[] nums) {
        return getInfo(nums, 0, nums.length - 1).mSum;
    }

    public Status getInfo(int[] arr, int left, int right) {
        if (left == right) {
            return new Status(arr[left], arr[left], arr[left], arr[left]);
        }
        int m = (left + right) >> 1;
        Status lSub = getInfo(arr, left, m);
        Status rSub = getInfo(arr, m + 1, right);
        return pushUp(lSub, rSub);
    }

    public Status pushUp(Status l, Status r) {
        int iSum = l.iSum + r.iSum;
        int lSum = Math.max(l.lSum, l.iSum + r.lSum);
        int rSum = Math.max(r.rSum, r.iSum + l.rSum);
        int mSum = Math.max(Math.max(l.mSum, r.mSum), l.rSum + r.lSum);
        return new Status(lSum, rSum, mSum, iSum);
    }

    public class Status {
        public int lSum, rSum, mSum, iSum;

        public Status(int lSum, int rSum, int mSum, int iSum) {
            this.lSum = lSum;
            this.rSum = rSum;
            this.mSum = mSum;
            this.iSum = iSum;
        }
    }

    // 对拍
    public int maxSubArray2(int[] nums) {
        int max = Integer.MIN_VALUE;
        for (int i = 0; i < nums.length; i++) {
            int sum = 0;
            for (int j = i; j < nums.length; j++) {
                sum = sum + nums[j];
                if (max < sum) {
                    max = sum;
                }
            }
        }
        return max;
    }

    public static void main(String[] args) {
        MaxSubArray object = new MaxSubArray();
        int[] num1 = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
        int ret = object.maxSubArray(num1);
        int ret2 = object.maxSubArray2(num1);
        System.out.println(ret);
        System.out.println(ret2);
    }
}
